using Furion.DependencyInjection;
using Furion.JsonSerialization;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Text.Encodings.Web;
using Newtonsoft.Json.Serialization;

namespace Utils
{
    public class NewtonsoftJsonSerializerProvider : IJsonSerializerProvider, ISingleton
    {
        /// <summary>
        /// 序列化对象
        /// </summary>
        /// <param name="value"></param>
        /// <param name="jsonSerializerOptions"></param>
        /// <returns></returns>
        public string Serialize(object value, object jsonSerializerOptions = null)
        {
            return JsonConvert.SerializeObject(value, (jsonSerializerOptions as JsonSerializerSettings) ?? GetDefaultJsonSerializerOptions());
        }

        /// <summary>
        /// 反序列化字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <param name="jsonSerializerOptions"></param>
        /// <returns></returns>
        public T Deserialize<T>(string json, object jsonSerializerOptions = null)
        {
            return JsonConvert.DeserializeObject<T>(json, (jsonSerializerOptions as JsonSerializerSettings)?? GetDefaultJsonSerializerOptions());
        }

        /// <summary>
        /// 默认配置
        /// </summary>
        /// <returns></returns>
        private static JsonSerializerSettings GetDefaultJsonSerializerOptions()
        {
            var setting = new JsonSerializerSettings
            {
                //WriteIndented = true,   // 缩进
                //Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,  // 中文乱码
                //PropertyNameCaseInsensitive = true  // 忽略大小写
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,//指定如何处理循环引用，None--不序列化，Error-抛出异常，Serialize--仍要序列化
                MissingMemberHandling = MissingMemberHandling.Ignore,//控制在反序列化期间如何处理缺少的成员（例如JSON包含对象上不是成员的属性）。 Ignore 忽略，error 报错
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Formatting = Formatting.Indented,//格式化 缩进
                MaxDepth = 10, //设置序列化的最大层数
                NullValueHandling = NullValueHandling.Ignore,//空值处理
                //日期类型默认格式化处理
                DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat,
                DateFormatString = "yyyy-MM-dd HH:mm:ss",

            };
           
            return setting;
        }
    }
}
